package scriptmodule;
import java.util.HashMap;

import java.io.ObjectStreamException;
import java.lang.reflect.Method;
import GameObj.GameObject;
public class scriptManager
{
	static public HashMap<String,Method> methodmap_ = new HashMap<String,Method>();
	
	static public void Init()
	{
		new ScriptInitializer();
	}
	
	static void RegisterFun(Class cls, String shortName)
	{
		String strClsName = cls.getName();
		Method[] methods = cls.getDeclaredMethods();
		for (int i = 0; i < methods.length; ++i)
		{
			String strMethodName = methods[i].getName();
			RegisterNameFun(shortName + "." + strMethodName, methods[i]);			
		}
		
		Class parentCls = cls.getSuperclass();
		if (parentCls != null && parentCls != Object.class)
		{
			RegisterFun(parentCls, shortName);
		}
	}
	
	static public boolean CallGameObjScript(GameObject gameObj, String strEvent,
			 Object ... args)
	{
		  String strInstName = gameObj.GetInstName();
		  
		  boolean bOK = false;
		  if (strInstName.length() > 0)
		  {
			  bOK = scriptManager.CallScript(strInstName + "." + strEvent, 
					  args);
		  }
		  
		  String templateName = gameObj.GetTemplateName();
		  if (templateName != null && templateName.length() > 0)
		  {
			  bOK = scriptManager.CallScript(templateName + "." + strEvent, 
					  args);		  
		  }
		return bOK;
	}
	
	static public boolean CallScript(String name, Object ... args)
	{
		boolean bRet = false;
		Method fun = methodmap_.get(name);
		if (fun == null)
		{
			return bRet;
		}
		try
		{			
			Object retObj = fun.invoke(null, args);
			if (retObj.getClass() == Boolean.class)
			{
				bRet = (Boolean)retObj;
				
			}
			/*if (retObj instanceof boolean)
			{
				bRet = 
				
			}*/
		}
		catch(Exception a)
		{
			
		}
		return bRet;
		
	}
	
	static public boolean ThisCallScript(String name, Object thisObject, Object ... args)
	{
		Method fun = methodmap_.get(name);
		if (fun == null)
		{
			return false;
		}
		try
		{			
			fun.invoke(thisObject, args);
		}
		catch(Exception a)
		{
			
		}
		return true;
		
	}
	
	static void RegisterNameFun(String name,Method fun)
	{
		methodmap_.put(name, fun);		
	}

}
